<style lang="scss"></style>

<script>
import dayjs from 'dayjs'
import PatrolPlanForm from './patrolPlanForm/index.vue'
import { patrolPlan, updatePatrolPlan } from '@/api/watchman'

export default {
  components: {
    PatrolPlanForm
  },
  props: {
    patrolId: {
      type: [Number, null],
      requried: true,
      default: null
    },
    value: {
      type: Boolean,
      required: true,
      default: false
    },
    title: {
      type: String,
      required: false,
      default: '修改巡防班次'
    },
    confirmText: {
      type: String,
      required: false,
      default: '保存'
    },
    cancelText: {
      type: String,
      required: false,
      default: '取消'
    }
  },
  data() {
    return {
      id: null,
      dialog: {},
      form: {
        form: {
          name: '',
          beginTime: null,
          endTime: null,
          number: 1,
          points: []
        },
        plans: []
      },
      loadingStatuses: {
        loading: false,
        isSavingPlans: false
      }
    }
  },
  computed: {
    dialogVisible: {
      get: function() {
        return this.value
      },
      set: function(visible) {
        this.$emit('input', visible)
      }
    },
    patrolPlansSorted() {
      return this.form.plans.concat().sort((range1, range2) => {
        return range1.beginTime.getTime() - range2.endTime.getTime()
      })
    },
    isShow() {
      return this.dialogVisible && typeof this.patrolId === 'number'
    },
    isActionDisabled() {
      const { loading, isSavingPlans } = this.loadingStatuses
      return loading || isSavingPlans
    }
  },
  watch: {
    isShow(isShow) {
      if (!isShow) return

      this.initData()
    }
  },
  created() {
  },
  methods: {
    async getPatrolPlan() {
      const result = await patrolPlan(this.patrolId)

      const {
        data: {
          name,
          time: times
        }
      } = result

      this.form.form.name = name
      this.form.plans = times.map(timeRange => {
        const currentDate = dayjs()
        const { start_time, end_time, sequence, drop } = timeRange
        return {
          beginTime: dayjs(`${currentDate.format('YYYY-MM-DD')} ${start_time}`).toDate(),
          endTime: dayjs(`${currentDate.format('YYYY-MM-DD')} ${end_time}`).toDate(),
          number: sequence,
          points: drop.map(point => {
            const { name, qrcode } = point
            return { name, QRCode: qrcode }
          })
        }
      })
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getPatrolPlan()
      ])

      const failTask = result.filter(task => task.status === 'rejected')
      if (failTask.length <= 0) return

      throw failTask.at(0).reason
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.sleep(500)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
        this.$message.error('获取失败')
      }
    },
    closeDialog() {
      if (this.loadingStatuses.isSavingPlans) { return }

      this.dialogVisible = false
    },
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    isObject(o) {
      return Object.prototype.toString.call(o) === '[object Object]'
    },
    buildParams() {
      const { patrolId, form: { form }, patrolPlansSorted } = this
      console.log(patrolPlansSorted)
      const plans = patrolPlansSorted.map(plan => {
        const { beginTime, endTime, points } = plan
        return {
          start_time: dayjs(beginTime).format('HH:MM:ss'),
          end_time: dayjs(endTime).format('HH:MM:ss'),
          drop: points.map(item => {
            return {
              name: item.name
            }
          })
        }
      })

      const params = {
        id: patrolId,
        name: form.name,
        times: JSON.stringify(plans)
      }

      return params
    },
    async savePlans() {
      try {
        this.loadingStatuses.isSavingPlans = true
        await this.sleep(300)

        const params = this.buildParams()
        await updatePatrolPlan(params)

        this.loadingStatuses.isSavingPlans = false
        this.closeDialog()
        this.$refs.patrolPlanForm?.resetForm?.()

        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.loadingStatuses.isSavingPlans = false
        this.$message.error(err.response?.data?.message ?? '修改失败')
      }
    }
  }
}

</script>

<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false"
  :before-close="closeDialog" width="35%" destroy-on-close>
    <div v-loading="isActionDisabled" class="body">
      <PatrolPlanForm ref="patrolPlanForm" v-model="form" />
    </div>

    <div slot="footer">
      <el-button
        type="primary"
        :loading="loadingStatuses.isSavingPlans"
        :disabled="isActionDisabled"
        @click="savePlans"
      >
        {{ confirmText }}
      </el-button>

      <el-button :disabled="loadingStatuses.isSavingPlans" @click="closeDialog">
        {{ cancelText }}
      </el-button>
    </div>
  </el-dialog>
</template>
